from django.shortcuts import render_to_response
from django.db.models import Q
from tasktracker.models import Category, CategoryForm, Task, TaskForm
from datetime  import datetime    

# update category
def update_category(category_id, category_code, category_description):
    ''' Update category '''
    c = Category.objects.get(id=category_id)
    c.code = category_code
    c.description = category_description
    c.save()


# manage categories
def manage_categories(request, category_id=None, action=None):
    '''  manage categories: create, edit, delete and view '''
    category_form = CategoryForm()
    search_criteria = ""

    if action == 'new':
        ''' create new category '''
        if request.method == "POST":
            category = CategoryForm(request.POST)
            # if form is not valid, return to edit form
            if not category.is_valid():
                return render_to_response('edit_category.html', { 'category': category, 'action': 'new' })
            # form is valid, save category
            category.save()
        else:
            category = CategoryForm()
            return render_to_response('edit_category.html', { 'category': category, 'action': 'new' })

    
    elif action == 'delete' and category_id > 0:
        Category.objects.get(pk=category_id).delete()
        
    elif action == 'edit' and category_id > 0:
        ''' edit category '''
        if request.method == "POST":
            update_category(int(request.POST['category_id']), \
                            request.POST['code'], request.POST['description'])
        else:
            category = CategoryForm(instance = Category.objects.get(pk=category_id))
            category.category_id = category_id
            return render_to_response('edit_category.html', { 'category': category })
        
    elif request.method == "POST":
        if request.POST.has_key('search'):
            search_criteria = request.POST['search']
        else:
            category_form = CategoryForm(request.POST)
            if category_form.is_valid():
                category_form.save()
                category_form = CategoryForm()

    ''' search categories '''
    if search_criteria:
        categories = Category.objects.filter(Q(description__contains=search_criteria) | \
                                            Q(code__contains=search_criteria)).order_by('-id')
    else:    
        categories = Category.objects.with_tasks_count()
    return render_to_response('view_categories.html', { 
                                                        'category_form': category_form, 
                                                        'categories': categories 
                                                    })

# update task
def update_task(task_id, task_description, task_category, task_status):
    ''' Update task '''

    t = Task.objects.get(id=task_id)
    t.description = task_description
    t.category = Category.objects.get(pk=task_category)
    t.status = task_status
    
    if task_status > 2:
        t.closed = datetime.now()
    t.save()

                                                    
# manage tasks
def manage_tasks(request, task_id=None, category_id=None, action=None):
    ''' manage tasks: create, edit, delete and view '''
    search_criteria = ""
    
    if category_id:
        tasks = Task.objects.open().filter(category=category_id)
        return render_to_response('view_tasks.html', { 'tasks': tasks, \
                                                        'view': 'tasks', \
                                                        'search_criteria': search_criteria})
    if action == 'new':
        """ create new task """
        if request.method == "POST":
            task = TaskForm(request.POST)
            # if form is not valid, return to edit form
            if not task.is_valid():
                return render_to_response('edit_task.html', { 'task': task, 'action': 'new' })
            # form is valid, save task
            task.save()
        else:
            task = TaskForm()
            return render_to_response('edit_task.html', { 'task': task, 'action': 'new' })

    elif action == 'edit' and task_id > 0:
        """ edit task """
        if request.method == "POST":
            update_task(int(request.POST['task_id']), request.POST['description'], \
                        request.POST['category'], request.POST['status'])
        else:
            task = TaskForm(instance = Task.objects.get(pk=task_id))
            task.task_id = task_id
            return render_to_response('edit_task.html', { 'task': task })

    elif action == 'completed' and task_id > 0:
        """ mark task as completed """
        t = Task.objects.get(id=task_id)
        t.status = 3
        t.closed = datetime.now()
        t.save()
        
        
    ''' search tasks '''
    if request.POST.has_key('search'):
        search_criteria = request.POST['search'] 
    if search_criteria:
        tasks = Task.objects.open().filter(Q(description__contains=search_criteria) | \
                                    Q(category__code__contains=search_criteria)).order_by('-id')
    else:    
        tasks = Task.objects.open().order_by('-id')
        
    return render_to_response('view_tasks.html', { 'tasks': tasks, \
                                                    'view': 'tasks', \
                                                    'search_criteria': search_criteria})

                                                    
# manage archived tasks (completed, failed, cancelled)
def manage_archive(request):
    '''  manage archived tasks: view '''
    search_criteria = ""
    
    if request.POST.has_key('search'):
        search_criteria = request.POST['search']

    if search_criteria:
        tasks = Task.objects.closed().order_by('-closed').filter(Q(description__contains=search_criteria) | \
                                                                Q(category__code__contains=search_criteria))
    else:    
        tasks = Task.objects.closed().order_by('-closed')

    return render_to_response('view_tasks.html', { 'tasks': tasks, 'view': 'archive' })
